package util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class UploadFileUtil {
    public static String upload(MultipartFile file, HttpServletRequest request, String uploadPath) {
        //获取文件存取路径
        String basePath = request.getServletContext().getRealPath(uploadPath);
        //构建文件对象，判断路径是否存在
        File directory = new File(basePath);
        if(!directory.exists()){
            directory.mkdirs();
        }
        //获取上传的文件名
        String fileName = file.getOriginalFilename();
        //h获取文件类型
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        //为上传的文件重新命名
        fileName = System.currentTimeMillis()+fileType;
        //保存用户上传的文件
        try {
            File uploadFile = new File(basePath + "/" + fileName);
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }
}
